﻿using DNFImagePacks2Manager.Helpers;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.IO;

namespace DNFImagePacks2Manager.Models
{
    public class BKItemSingle(string filename) : BKItemBase(Path.GetFileNameWithoutExtension(filename), "单品")
    {
        public string Suffix { get; set; } = Path.GetExtension(filename);
        public string FileName { get; set; } = filename;
        public virtual string BKFile  => Path.Combine(BKHelper.GetSingleFolder(), FileName);

        public override async void Apply(Page page)
        {
            if (!LocalStorageHelper.IsSetDNFPath())
            {
                DialogHelper.ShowErrorMessage(page, "应用失败: 未设置DNF路径");
                return;
            }

            StackPanel stackPanel = new();

            var categories = BKPathHelper.CategoryList;

            List<BKPathCategory> firstDictionary = [new("未选择", [])];
            firstDictionary.AddRange(categories);

            ComboBox comboBoxFirst = new()
            {
                ItemsSource = firstDictionary,
                Margin = new Thickness(10, 0, 0, 0),
                Width = 200,
                DisplayMemberPath = "name"
            };
            ComboBox comboBoxSecond = new() {
                Margin = new Thickness(10, 0, 0, 0),
                Width = 200,
                DisplayMemberPath = "name"
            };
            ComboBox comboBoxThird = new()
            {
                Margin = new Thickness(10, 0, 0, 0),
                Width = 200,
                DisplayMemberPath = "name"
            };
            comboBoxFirst.SelectionChanged += (sender, e) =>
            {
                if (comboBoxFirst.SelectedItem is BKPathCategory selected)
                {
                    comboBoxSecond.ItemsSource = null;
                    List<BKPathCategorySub> secondDictionary = [];
                    secondDictionary.Add(new("未选择", []));
                    secondDictionary.AddRange(selected.list);
                    comboBoxSecond.ItemsSource = secondDictionary;
                    comboBoxSecond.SelectedIndex = 0;
                }
            };
            comboBoxSecond.SelectionChanged += (sender, e) =>
            {
                if (comboBoxSecond.SelectedItem is BKPathCategorySub selected)
                {
                    comboBoxThird.ItemsSource = null;
                    List<BKPathItem> thirdDictionary = [];
                    thirdDictionary.Add(new("未选择", ""));
                    thirdDictionary.AddRange(selected.list);
                    comboBoxThird.ItemsSource = thirdDictionary;
                    comboBoxThird.SelectedIndex = 0;
                }
            };

            StackPanel stackPanel1 = new()
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0, 10, 0, 0)
            };

            StackPanel stackPanel2 = new()
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0, 10, 0, 0)
            };

            StackPanel stackPanel3 = new()
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0, 10, 0, 0)
            };
            TextBlock textBlock1 = new()
            {
                Text = "大类: ",
                VerticalAlignment = VerticalAlignment.Center
            };
            TextBlock textBlock2 = new()
            {
                Text = "子类: ",
                VerticalAlignment = VerticalAlignment.Center
            };
            TextBlock textBlock3 = new()
            {
                Text = "类型: ",
                VerticalAlignment = VerticalAlignment.Center
            };

            stackPanel1.Children.Add(textBlock1);
            stackPanel1.Children.Add(comboBoxFirst);
            stackPanel2.Children.Add(textBlock2);
            stackPanel2.Children.Add(comboBoxSecond);
            stackPanel3.Children.Add(textBlock3);
            stackPanel3.Children.Add(comboBoxThird);

            stackPanel.Children.Add(stackPanel1);
            stackPanel.Children.Add(stackPanel2);
            stackPanel.Children.Add(stackPanel3);

            comboBoxFirst.SelectedIndex = 0;
            ContentDialogResult result = await DialogHelper.ShowConfirmDialog(page, "请选择要应用到的类型", stackPanel);
            if (result == ContentDialogResult.Primary)
            {
                if (comboBoxThird.SelectedItem is BKPathItem selected)
                {
                    if (selected == null || selected.path.Length == 0)
                    {
                        DialogHelper.ShowErrorMessage(page, $" 应用失败: 未选择类型");
                    }
                    else {
                        string bkFile = BKFile;
                        string bkPath = LocalStorageHelper.GetBKOfficialPath();
                        string targetFile = Path.Combine(bkPath, selected.path);

                        try
                        {
                            if (File.Exists(targetFile))
                            {
                                File.Delete(targetFile);
                            }
                            File.Copy(bkFile, targetFile);
                            DialogHelper.ShowSuccessMessage(page, "应用成功");
                        }
                        catch (Exception ex)
                        {
                            DialogHelper.ShowErrorMessage(page, $"应用失败: {ex.Message}");
                        }
                    }
                }
            }
        }

        public override bool Delete(Page page)
        {
            try
            {
                string file = BKFile;
                if (File.Exists(file)) {
                    File.Delete(file);
                }
                DialogHelper.ShowSuccessMessage(page, "删除成功");
                return true;
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"删除失败: {ex.Message}");
                return false;
            }
        }

        public override bool Rename(Page page, string name)
        {
            try
            {
                string file = BKFile;
                string newFileName = name + Suffix;
                string newFile = Path.Combine(BKHelper.GetSingleFolder(), newFileName);
                if (File.Exists(file))
                {
                    if (File.Exists(newFile))
                    {
                        DialogHelper.ShowErrorMessage(page, "重命名失败: 目标文件已存在");
                    }
                    else
                    {
                        File.Move(file, newFile);
                        FileName = newFileName;
                        Name = name;
                        DialogHelper.ShowSuccessMessage(page, "重命名完成");
                        return true;
                    }
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, "重命名失败: 找不到文件");
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"重命名失败: {ex.Message}");
            }
            return false;
        }

        public override async void Preview(Page page)
        {
            try
            {
                string file = BKFile;
                if (File.Exists(file))
                {
                    int type = BKHelper.GetType(file);
                    switch (type)
                    {
                        case 1:
                        case 2:
                            await BinkPlayHelper.PlayWithBinkPlay(page, file, true);
                            break;
                        case 0:
                            //BKFile bkFile = new BKFile(file);
                            //string tempFile = await bkFile.WriteToTempFile();
                            //ConsoleHelper.OpenFolderAndSelectFile(tempFile);
                            //break;
                        case -1:
                        default:
                            DialogHelper.ShowErrorMessage(page, "预览失败: 未识别的文件格式");
                            break;
                    }
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, "预览失败: 找不到文件");
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"预览失败: {ex.Message}");
            }
        }

        public override void Edit(Page page)
        {
            DialogHelper.ShowErrorMessage(page, "单品文件不支持编辑");
            return;
        }

        public override void Export(Page page)
        {
            try
            {
                string file = BKFile;
                if (File.Exists(file))
                {
                    DialogHelper.ShowSavePickerAndSaveFile(page, Name, "BK2 补丁文件", Suffix, file);
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, "导出失败: 找不到文件");
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"导出失败: {ex.Message}");
            }
        }
    }
}